package ldh.im.fxbase.util;

import ldh.im.fxbase.data.pojo.ImMessage;
import ldh.im.fxbase.data.pojo.MessageExt;
import ldh.im.util.ConfigUtil;
import ldh.rpc.util.JsonUtil;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class JarUtil {

    public static boolean isJarFile(String url) {
        return url.startsWith("jar:");
    }

    public static String readContent(String jarFileUrl) throws IOException {
        if (jarFileUrl.startsWith("jar:")) {
            int idx = jarFileUrl.indexOf("!");
            String jarFilePath = jarFileUrl.substring(10, idx);
            String file = jarFileUrl.substring(idx+2);
            JarFile jarFile = new JarFile(jarFilePath);
            for(Enumeration<JarEntry> enumeration = jarFile.entries(); enumeration.hasMoreElements();) {
                JarEntry jarEntry = enumeration.nextElement();
                if (jarEntry.getName().equals(file)) {
                    try (InputStream inputStream = jarFile.getInputStream(jarEntry);
                         BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream)
                    ) {
                        String sql = new String(bufferedInputStream.readAllBytes(), "utf8");
                        return sql;
                    }
                }
            }
        }
        return null;
    }
}
